package com.yuzhyn.hiops.app.application.service;

import com.yuzhyn.azylee.core.datas.collections.ListTool;
import com.yuzhyn.hiops.common.entity.SysMenu;
import com.yuzhyn.hiops.common.mapper.SysMenuMapper;
import com.yuzhyn.hiops.common.model.SysMenuTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysMenuService {

    @Autowired
    SysMenuMapper sysMenuMapper;

    public List<SysMenuTree> getMenuTree(String userId) {
        List<SysMenuTree> trees = new ArrayList<>();
        List<SysMenu> menuList = sysMenuMapper.selectList(null);

        if (ListTool.ok(menuList)) {
            for (SysMenu item : menuList) {
                SysMenuTree tree = new SysMenuTree();
                tree.setRoot(item);
                tree.setNodes(new ArrayList<>());
                if (item.getParentId().equals("0")) tree.setLevel(1);
                trees.add(tree);
            }

            for (SysMenuTree root : trees) {
                for (SysMenuTree node : trees) {
                    if (root.getRoot().getId().equals(node.getRoot().getParentId())) {
                        root.getNodes().add(node);
                    }
                }
            }


            for (int i = trees.size() - 1; i >= 0; i--) {
                if (1 != trees.get(i).getLevel()) {
                    trees.remove(i);
                }
            }

        }
        return trees;
    }
}
